<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample</title>
<meta name="viewport"
            content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="true">
</head>
<body>
<canvas id="myCanvas" width="300" height="150"
        style="border:1px dashed #c3c3c3;">
   这里放置的内容用于浏览器不支持Canvas的情况
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
if (canvas && canvas.getContext) {
   var cxt = canvas.getContext("2d");
   // 创建image
   var img = new Image();
   img.src = "images/icon_ch.png";
   // 当图片加载完毕再绘制图片
   img.onload = function (event){
	  cxt.drawImage(img, 0, 0);
	  // ======================================================
	  // 下面是实现反相
	  // 首先获取ImageData对象，因为刚才画的图片的幅面是109*109
	  // 所以，指定幅面大小也是109*109
	  var imgd = cxt.getImageData(0, 0, 109, 109);
	  var pix = imgd.data;

	  // 遍历每个像素和设置反相
	  var n = pix.length;
	  for (var i = 0; i < n; i += 4) {
	     pix[i  ] = 255 - pix[i  ];  // R
	     pix[i+1] = 255 - pix[i+1]; // G
	     pix[i+2] = 255 - pix[i+2]; // B
	     // i+3是alpha
	  }

	  // 画ImageData对象
	  cxt.putImageData(imgd, 109, 0);
   }
}
</script>
</body>
</html>
